<!-- xl-bluetooth 蓝牙连接组件 -->
<template>
  <view class="xl-bluetooth-container">
    <!-- 蓝牙状态显示 -->
    <view class="bluetooth-status">
      <view class="status-indicator" :class="{ 'active': isBluetoothEnabled }"></view>
      <text class="status-text">{{ statusText }}</text>
      <view class="action-btn" @click="toggleBluetooth">
        {{ isBluetoothEnabled ? '关闭蓝牙' : '打开蓝牙' }}
      </view>
    </view>
    
    <!-- 设备列表和扫描按钮 -->
    <view class="device-section">
      <view class="section-header">
        <text class="section-title">设备列表</text>
        <view class="scan-btn" @click="startScan" v-if="isBluetoothEnabled">
          <text>{{ isScanning ? '扫描中...' : '扫描设备' }}</text>
          <view class="loader" v-if="isScanning"></view>
        </view>
      </view>
      
      <!-- 设备列表 -->
      <scroll-view class="device-list" scroll-y>
        <view v-if="devices.length === 0" class="empty-list">
          <text>{{ isScanning ? '正在搜索...' : '暂无设备' }}</text>
        </view>
        <view 
          v-for="(device, index) in devices" 
          :key="index" 
          class="device-item"
          :class="{ 'connected': device.connected }"
          @click="connectDevice(device)"
        >
          <view class="device-icon" :class="{ 'connected': device.connected }">
            <view class="signal-strength" :style="{ width: `${device.RSSI ? Math.min(100, Math.max(0, (device.RSSI + 100) * 2)) : 0}%` }"></view>
          </view>
          <view class="device-info">
            <text class="device-name">{{ device.name || device.deviceId || '未知设备' }}</text>
            <text class="device-id">{{ device.deviceId }}</text>
          </view>
          <view class="device-status">
            <text>{{ device.connected ? '已连接' : '点击连接' }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 已连接设备信息 -->
    <view class="connected-device" v-if="connectedDevice">
      <view class="section-header">
        <text class="section-title">已连接设备</text>
        <view class="disconnect-btn" @click="disconnectDevice">断开连接</view>
      </view>
      
      <view class="device-detail">
        <view class="detail-row">
          <text class="detail-label">设备名称</text>
          <text class="detail-value">{{ connectedDevice.name || '未命名设备' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">设备ID</text>
          <text class="detail-value">{{ connectedDevice.deviceId }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">信号强度</text>
          <text class="detail-value">{{ connectedDevice.RSSI || 'N/A' }} dBm</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">连接状态</text>
          <text class="detail-value">已连接</text>
        </view>
      </view>
      
      <!-- 设备操作部分 -->
      <view class="device-operations">
        <view class="operation-btn" @click="sendTestData">
          发送测试数据
        </view>
        <view class="operation-btn" @click="readDeviceData">
          读取设备数据
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';

// 蓝牙状态
const isBluetoothEnabled = ref(false);
const isScanning = ref(false);
const devices = ref([]);
const connectedDevice = ref(null);
const bluetoothAdapter = ref(null);

// 蓝牙管理类 - 用于外部调用
class BluetoothManager {
  constructor(refs) {
    // 使用闭包保存refs
    this._refs = refs;
  }

  // 获取当前状态
  getStatus() {
    return {
      isEnabled: this._refs.isBluetoothEnabled.value,
      isScanning: this._refs.isScanning.value,
      devices: this._refs.devices.value,
      connectedDevice: this._refs.connectedDevice.value
    };
  }
  
  // 初始化蓝牙模块
  async initialize(options = {}) {
    return initBluetooth()
      .then(() => {
        if (options.success) options.success();
      })
      .catch(err => {
        if (options.fail) options.fail(err);
      });
  }
  
  // 开始扫描设备
  async startScan(options = {}) {
    return startScan()
      .then(() => {
        if (options.success) options.success();
      })
      .catch(err => {
        if (options.fail) options.fail(err);
      });
  }
  
  // 停止扫描
  async stopScan(options = {}) {
    return stopScan()
      .then(() => {
        if (options.success) options.success();
      })
      .catch(err => {
        if (options.fail) options.fail(err);
      });
  }
  
  // 连接设备
  async connect(deviceId, options = {}) {
    const device = this._refs.devices.value.find(d => d.deviceId === deviceId);
    if (!device) {
      if (options.fail) options.fail(new Error('设备未找到'));
      return;
    }
    
    return connectDevice(device)
      .then(() => {
        if (options.success) options.success();
      })
      .catch(err => {
        if (options.fail) options.fail(err);
      });
  }
  
  // 断开连接
  async disconnect(options = {}) {
    return disconnectDevice()
      .then(() => {
        if (options.success) options.success();
      })
      .catch(err => {
        if (options.fail) options.fail(err);
      });
  }
  
  // 发送数据
  async sendData(data, options = {}) {
    if (!this._refs.connectedDevice.value) {
      if (options.fail) options.fail(new Error('设备未连接'));
      return;
    }
    
    return sendTestData()
      .then(() => {
        if (options.success) options.success();
      })
      .catch(err => {
        if (options.fail) options.fail(err);
      });
  }
  
  // 读取数据
  async readData(options = {}) {
    if (!this._refs.connectedDevice.value) {
      if (options.fail) options.fail(new Error('设备未连接'));
      return;
    }
    
    return readDeviceData()
      .then(() => {
        if (options.success) options.success();
      })
      .catch(err => {
        if (options.fail) options.fail(err);
      });
  }
}

// 创建xlBluetooth对象
const xlBluetooth = {
  create() {
    // 传入所有需要的refs
    return new BluetoothManager({
      isBluetoothEnabled,
      isScanning,
      devices,
      connectedDevice,
      bluetoothAdapter
    });
  }
};

// 导出方法和管理器类
defineExpose({
  // 导出工厂方法
  create: xlBluetooth.create,
  // 导出直接方法
  initBluetooth,
  startScan,
  stopScan,
  connectDevice,
  disconnectDevice,
  sendTestData,
  readDeviceData
});

// 计算蓝牙状态文本
const statusText = computed(() => {
  if (isBluetoothEnabled.value) {
    if (isScanning.value) {
      return '蓝牙已开启，正在扫描...';
    }
    return '蓝牙已开启';
  }
  return '蓝牙未开启';
});

// 初始化蓝牙
const initBluetooth = async () => {
  try {
    // H5环境不支持蓝牙功能
    // #ifdef H5
    uni.showModal({
      title: '提示',
      content: 'H5环境不支持蓝牙功能，请在APP或小程序中使用',
      showCancel: false
    });
    return false;
    // #endif

    // 先检查权限（仅在APP环境）
    // #ifdef APP-PLUS
    await checkBluetoothPermission();
    // #endif

    // 检查微信小程序环境的蓝牙权限
    // #ifdef MP-WEIXIN
    try {
      await uni.getSetting({
        success: (res) => {
          // 如果没有蓝牙权限，引导用户授权
          if (!res.authSetting['scope.bluetooth']) {
            uni.authorize({
              scope: 'scope.bluetooth',
              success: () => {
                console.log('蓝牙权限授权成功');
              },
              fail: (err) => {
                console.error('蓝牙权限授权失败:', err);
                uni.showModal({
                  title: '提示',
                  content: '需要获取您的蓝牙权限，请在设置中打开"蓝牙"权限',
                  confirmText: '去设置',
                  success: (res) => {
                    if (res.confirm) {
                      uni.openSetting();
                    }
                  }
                });
                throw new Error('bluetooth permission denied');
              }
            });
          }
        }
      });
    } catch (authError) {
      console.error('蓝牙权限检查失败:', authError);
    }
    // #endif
    
    // 打开蓝牙前先检查系统蓝牙是否开启
    // #ifdef MP-WEIXIN
    try {
      const bleState = await new Promise((resolve, reject) => {
        wx.getBluetoothAdapterState({
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        });
      });
      
      if (!bleState.available) {
        uni.showModal({
          title: '提示',
          content: '请先开启手机蓝牙',
          showCancel: false
        });
        throw new Error('bluetooth not available');
      }
    } catch (stateError) {
      // 如果是蓝牙未开启，提供更明确的错误信息
      if (stateError.errCode === 10001) {
        uni.showToast({
          title: '请先开启手机蓝牙',
          icon: 'none',
          duration: 2000
        });
        isBluetoothEnabled.value = false;
        return false;
      }
    }
    // #endif
    
    // 初始化蓝牙模块前增加延迟（解决某些设备初始化太快的问题）
    await new Promise(resolve => setTimeout(resolve, 200));
    
    // 初始化蓝牙模块
    console.log('开始初始化蓝牙适配器...');
    const res = await uni.openBluetoothAdapter();
    console.log('蓝牙适配器初始化成功:', res);
    bluetoothAdapter.value = res;
    isBluetoothEnabled.value = true;
    
    // 监听蓝牙状态变化
    uni.onBluetoothAdapterStateChange((res) => {
      console.log('蓝牙状态变化:', res);
      isBluetoothEnabled.value = res.available;
      if (!res.available) {
        // 蓝牙关闭时停止扫描、清空设备列表
        isScanning.value = false;
        devices.value = [];
        connectedDevice.value = null;
      }
    });
    
    // 监听设备发现事件
    uni.onBluetoothDeviceFound((res) => {
      if (!res.devices || res.devices.length === 0) return;
      
      res.devices.forEach(device => {
        // 检查是否已存在该设备
        const existingIndex = devices.value.findIndex(d => d.deviceId === device.deviceId);
        
        if (existingIndex >= 0) {
          // 更新现有设备信息
          devices.value[existingIndex] = {
            ...devices.value[existingIndex],
            ...device,
            lastSeen: Date.now()
          };
        } else {
          // 添加新设备
          devices.value.push({
            ...device,
            connected: false,
            lastSeen: Date.now()
          });
        }
      });
      
      // 按信号强度排序
      devices.value.sort((a, b) => (b.RSSI || -100) - (a.RSSI || -100));
    });
    
    return true;
  } catch (error) {
    console.error('初始化蓝牙失败:', error);
    isBluetoothEnabled.value = false;
    
    // 根据错误码显示不同提示
    let errorMsg = '蓝牙初始化失败';
    let errorDetail = '';
    
    if (error.errCode === 12 || error.errCode === 10001) {
      errorMsg = '蓝牙未开启，请先打开手机蓝牙';
    } else if (error.errCode === 10008 || error.errCode === 10009) {
      errorMsg = '蓝牙初始化失败，需要开启定位权限';
    } else if (error.errMsg && error.errMsg.includes('permission')) {
      errorMsg = '蓝牙权限被拒绝，请前往设置开启';
    }
    
    // #ifdef MP-WEIXIN
    // 处理微信小程序特有的错误
    if (error.errCode === 10000) {
      errorMsg = '当前蓝牙适配器不可用';
      errorDetail = '请检查手机蓝牙是否正常工作';
    } else if (error.errCode === 10001) {
      errorMsg = '未找到蓝牙适配器';
      errorDetail = '请确保已开启手机蓝牙';
    } else if (error.errCode === 10002) {
      errorMsg = '连接超时';
      errorDetail = '请重试或确认设备是否在范围内';
    } else if (error.errCode === 10003) {
      errorMsg = '蓝牙功能暂不可用';
      errorDetail = '请稍后再试';
    } else if (error.errCode === 10004) {
      errorMsg = '没有找到指定设备';
      errorDetail = '请确认设备已打开并在范围内';
    } else if (error.errCode === 10005) {
      errorMsg = '连接失败';
      errorDetail = '请重试或检查设备状态';
    } else if (error.errCode === 10006) {
      errorMsg = '没有找到指定服务';
      errorDetail = '设备可能不支持该服务';
    } else if (error.errCode === 10007) {
      errorMsg = '没有找到指定特征值';
      errorDetail = '设备可能不支持该特征值';
    } else if (error.errCode === 10010) {
      errorMsg = '已断开连接';
      errorDetail = '与设备的连接已断开';
    } else if (error.errCode === 10011 || error.errCode === 10012) {
      errorMsg = '操作超时';
      errorDetail = '请重试或检查设备状态';
    } else if (error.errCode === 10013) {
      errorMsg = '连接不存在';
      errorDetail = '请先创建连接';
    }
    // #endif
    
    console.error(`蓝牙初始化错误 [${error.errCode}]: ${error.errMsg}`);
    
    uni.showModal({
      title: errorMsg,
      content: errorDetail || '请确保蓝牙已开启且授予了相应权限',
      confirmText: '我知道了',
      showCancel: false
    });
    
    return false;
  }
};

// 检查蓝牙权限
const checkBluetoothPermission = async () => {
  // #ifdef APP-PLUS
  try {
    // Android平台需要定位权限
    const isAndroid = uni.getSystemInfoSync().platform === 'android';
    if (isAndroid) {
      // 检查并请求定位权限
      const locationPermission = await requestPermission('android.permission.ACCESS_FINE_LOCATION');
      if (!locationPermission) {
        throw new Error('location permission denied');
      }
      
      // Android 12及以上还需要蓝牙扫描/连接权限
      const androidVersion = parseInt(uni.getSystemInfoSync().system.match(/\d+/)[0]);
      if (androidVersion >= 12) {
        const scanPermission = await requestPermission('android.permission.BLUETOOTH_SCAN');
        const connectPermission = await requestPermission('android.permission.BLUETOOTH_CONNECT');
        if (!scanPermission || !connectPermission) {
          throw new Error('bluetooth permission denied');
        }
      }
    }
    return true;
  } catch (error) {
    console.error('权限检查失败:', error);
    uni.showModal({
      title: '权限提醒',
      content: '使用蓝牙功能需要开启蓝牙和定位权限',
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          // 跳转到系统设置页面
          if (plus.os.name.toLowerCase() === 'android') {
            // Android跳转到应用权限设置页面
            const main = plus.android.runtimeMainActivity();
            const Intent = plus.android.importClass('android.content.Intent');
            const Settings = plus.android.importClass('android.provider.Settings');
            const Uri = plus.android.importClass('android.net.Uri');
            const intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            const uri = Uri.fromParts('package', main.getPackageName(), null);
            intent.setData(uri);
            main.startActivity(intent);
          } else {
            // iOS跳转到系统设置页面
            const UIApplication = plus.ios.import('UIApplication');
            const application = UIApplication.sharedApplication();
            const NSURL = plus.ios.import('NSURL');
            const setting_url = NSURL.URLWithString('app-settings:');
            application.openURL(setting_url);
            plus.ios.deleteObject(setting_url);
            plus.ios.deleteObject(NSURL);
            plus.ios.deleteObject(application);
          }
        }
      }
    });
    throw error;
  }
  // #endif
  
  // #ifdef MP-WEIXIN
  try {
    // 微信小程序检查是否有蓝牙权限
    const res = await uni.authorize({
      scope: 'scope.bluetooth'
    });
    return true;
  } catch (error) {
    uni.showModal({
      title: '提示',
      content: '使用蓝牙功能需要您的授权',
      confirmText: '去授权',
      success: (res) => {
        if (res.confirm) {
          uni.openSetting();
        }
      }
    });
    throw error;
  }
  // #endif
  
  // #ifdef H5
  // H5平台需要用户手动授权，一般通过按钮点击后触发API调用完成授权
  return true;
  // #endif
  
  return true;
};

// 请求权限（仅APP可用）
const requestPermission = (permissionName) => {
  // #ifdef APP-PLUS
  return new Promise((resolve, reject) => {
    plus.android.requestPermissions(
      [permissionName],
      function(resultObj) {
        const result = resultObj.granted.indexOf(permissionName) >= 0;
        resolve(result);
      },
      function(error) {
        resolve(false);
      }
    );
  });
  // #endif
  
  // 其他平台返回true
  return Promise.resolve(true);
};

// 开始扫描设备
const startScan = async () => {
  try {
    // 检查蓝牙是否已开启
    if (!isBluetoothEnabled.value) {
      throw new Error('蓝牙未开启');
    }
    
    // 如果已经在扫描，先停止
    if (isScanning.value) {
      await stopScan();
    }
    
    // 清空设备列表
    devices.value = [];
    isScanning.value = true;
    
    // 显示加载提示
    uni.showLoading({ title: '搜索中...' });
    
    // 开始搜索设备
    await uni.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      powerLevel: 'high',
    });
    
    // 监听设备发现事件
    uni.onBluetoothDeviceFound((res) => {
      if (!res.devices || res.devices.length === 0) return;
      
      res.devices.forEach(device => {
        // 检查设备是否已在列表中
        const existingIndex = devices.value.findIndex(d => d.deviceId === device.deviceId);
        
        if (existingIndex >= 0) {
          // 更新现有设备信息
          devices.value[existingIndex] = {
            ...devices.value[existingIndex],
            ...device,
            lastSeen: Date.now()
          };
        } else {
          // 添加新设备
          devices.value.push({
            ...device,
            connected: false,
            lastSeen: Date.now()
          });
        }
        
        // 按信号强度排序
        devices.value.sort((a, b) => (b.RSSI || -100) - (a.RSSI || -100));
      });
    });

    // 设置搜索超时
    setTimeout(async () => {
      try {
        await stopScan();
      } catch (error) {
        console.error('停止扫描失败:', error);
      }
    }, 10000);
  } catch (error) {
    console.error('开始扫描失败:', error);
    isScanning.value = false;
    uni.hideLoading();
    uni.showToast({
      title: error.message || '搜索设备失败',
      icon: 'none'
    });
  }
};

// 停止扫描
const stopScan = async () => {
  try {
    if (!isScanning.value) return;
    
    await uni.stopBluetoothDevicesDiscovery();
    isScanning.value = false;
    uni.hideLoading();
  } catch (error) {
    console.error('停止扫描失败:', error);
    isScanning.value = false;
    uni.hideLoading();
    throw error;
  }
};

// 连接设备
const connectDevice = async (device) => {
  if (device.connected) {
    uni.showToast({
      title: '设备已连接',
      icon: 'none'
    });
    return;
  }
  
  // 停止扫描
  await stopScan();
  
  uni.showLoading({
    title: '正在连接...'
  });
  
  try {
    // 创建BLE连接
    await uni.createBLEConnection({
      deviceId: device.deviceId
    });
    
    // 更新设备连接状态
    const index = devices.value.findIndex(d => d.deviceId === device.deviceId);
    if (index >= 0) {
      devices.value[index].connected = true;
      connectedDevice.value = devices.value[index];
    }
    
    uni.hideLoading();
    uni.showToast({
      title: '连接成功',
      icon: 'success'
    });
    
    // 获取设备的服务
    getDeviceServices(device.deviceId);
  } catch (error) {
    uni.hideLoading();
    console.error('连接设备失败:', error);
    uni.showToast({
      title: '连接失败: ' + (error.errMsg || '未知错误'),
      icon: 'none'
    });
  }
};

// 断开连接
const disconnectDevice = async () => {
  if (!connectedDevice.value) return;
  
  uni.showLoading({
    title: '断开连接中...'
  });
  
  try {
    await uni.closeBLEConnection({
      deviceId: connectedDevice.value.deviceId
    });
    
    // 更新设备连接状态
    const index = devices.value.findIndex(d => d.deviceId === connectedDevice.value.deviceId);
    if (index >= 0) {
      devices.value[index].connected = false;
    }
    
    connectedDevice.value = null;
    
    uni.hideLoading();
    uni.showToast({
      title: '已断开连接',
      icon: 'success'
    });
  } catch (error) {
    uni.hideLoading();
    console.error('断开连接失败:', error);
    uni.showToast({
      title: '断开连接失败: ' + (error.errMsg || '未知错误'),
      icon: 'none'
    });
  }
};

// 获取设备服务
const getDeviceServices = async (deviceId) => {
  try {
    const res = await uni.getBLEDeviceServices({
      deviceId
    });
    
    if (res.services && res.services.length > 0) {
      // 保存设备服务信息
      const index = devices.value.findIndex(d => d.deviceId === deviceId);
      if (index >= 0) {
        devices.value[index].services = res.services;
        if (connectedDevice.value && connectedDevice.value.deviceId === deviceId) {
          connectedDevice.value.services = res.services;
        }
      }
      
      // 获取每个服务的特征值
      res.services.forEach(service => {
        getServiceCharacteristics(deviceId, service.uuid);
      });
    }
  } catch (error) {
    console.error('获取设备服务失败:', error);
  }
};

// 获取服务特征值
const getServiceCharacteristics = async (deviceId, serviceId) => {
  try {
    const res = await uni.getBLEDeviceCharacteristics({
      deviceId,
      serviceId
    });
    
    if (res.characteristics && res.characteristics.length > 0) {
      // 保存特征值信息
      const deviceIndex = devices.value.findIndex(d => d.deviceId === deviceId);
      if (deviceIndex >= 0) {
        if (!devices.value[deviceIndex].characteristics) {
          devices.value[deviceIndex].characteristics = {};
        }
        devices.value[deviceIndex].characteristics[serviceId] = res.characteristics;
        
        if (connectedDevice.value && connectedDevice.value.deviceId === deviceId) {
          if (!connectedDevice.value.characteristics) {
            connectedDevice.value.characteristics = {};
          }
          connectedDevice.value.characteristics[serviceId] = res.characteristics;
        }
      }
    }
  } catch (error) {
    console.error('获取服务特征值失败:', error);
  }
};

// 发送测试数据
const sendTestData = async () => {
  if (!connectedDevice.value || !connectedDevice.value.services) {
    uni.showToast({
      title: '设备未连接或无服务可用',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 查找可写的特征值
    let serviceId = null;
    let characteristicId = null;
    
    if (connectedDevice.value.characteristics) {
      for (const sId in connectedDevice.value.characteristics) {
        const chars = connectedDevice.value.characteristics[sId];
        for (const char of chars) {
          if (char.properties.write || char.properties.writeNoResponse) {
            serviceId = sId;
            characteristicId = char.uuid;
            break;
          }
        }
        if (serviceId) break;
      }
    }
    
    if (!serviceId || !characteristicId) {
      uni.showToast({
        title: '未找到可写入的特征值',
        icon: 'none'
      });
      return;
    }
    
    // 发送测试数据
    const buffer = new ArrayBuffer(4);
    const dataView = new DataView(buffer);
    dataView.setUint32(0, 0x12345678); // 测试数据
    
    await uni.writeBLECharacteristicValue({
      deviceId: connectedDevice.value.deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      value: buffer
    });
    
    uni.showToast({
      title: '数据发送成功',
      icon: 'success'
    });
  } catch (error) {
    console.error('发送数据失败:', error);
    uni.showToast({
      title: '发送数据失败: ' + (error.errMsg || '未知错误'),
      icon: 'none'
    });
  }
};

// 读取设备数据
const readDeviceData = async () => {
  if (!connectedDevice.value || !connectedDevice.value.services) {
    uni.showToast({
      title: '设备未连接或无服务可用',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 查找可读的特征值
    let serviceId = null;
    let characteristicId = null;
    
    if (connectedDevice.value.characteristics) {
      for (const sId in connectedDevice.value.characteristics) {
        const chars = connectedDevice.value.characteristics[sId];
        for (const char of chars) {
          if (char.properties.read) {
            serviceId = sId;
            characteristicId = char.uuid;
            break;
          }
        }
        if (serviceId) break;
      }
    }
    
    if (!serviceId || !characteristicId) {
      uni.showToast({
        title: '未找到可读取的特征值',
        icon: 'none'
      });
      return;
    }
    
    // 启用通知
    await uni.notifyBLECharacteristicValueChange({
      deviceId: connectedDevice.value.deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      state: true
    });
    
    // 监听特征值变化
    uni.onBLECharacteristicValueChange((res) => {
      console.log('收到数据:', ab2hex(res.value));
      uni.showToast({
        title: '接收到数据: ' + ab2hex(res.value),
        icon: 'none'
      });
    });
    
    // 读取特征值
    await uni.readBLECharacteristicValue({
      deviceId: connectedDevice.value.deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId
    });
  } catch (error) {
    console.error('读取数据失败:', error);
    uni.showToast({
      title: '读取数据失败: ' + (error.errMsg || '未知错误'),
      icon: 'none'
    });
  }
};

// 开关蓝牙
const toggleBluetooth = async () => {
  if (isBluetoothEnabled.value) {
    // 关闭蓝牙
    try {
      await uni.closeBluetoothAdapter();
      isBluetoothEnabled.value = false;
      devices.value = [];
      connectedDevice.value = null;
      
      uni.showToast({
        title: '蓝牙已关闭',
        icon: 'success'
      });
    } catch (error) {
      console.error('关闭蓝牙失败:', error);
      uni.showToast({
        title: '关闭蓝牙失败',
        icon: 'none'
      });
    }
  } else {
    // 开启蓝牙
    try {
      // 在小程序中，引导用户开启蓝牙
      // #ifdef MP-WEIXIN
      try {
        const bleState = await new Promise((resolve, reject) => {
          wx.getBluetoothAdapterState({
            success: (res) => resolve(res),
            fail: (err) => reject(err)
          });
        });
        
        if (!bleState.available) {
          uni.showModal({
            title: '提示',
            content: '请先开启手机蓝牙',
            confirmText: '我知道了',
            showCancel: false
          });
          return;
        }
      } catch (stateError) {
        // 错误处理
        if (stateError.errCode === 10001) {
          uni.showModal({
            title: '提示',
            content: '请先开启手机蓝牙',
            confirmText: '我知道了',
            showCancel: false
          });
          return;
        } 
      }
      // #endif
      
      // 在APP中检查系统蓝牙状态
      // #ifdef APP-PLUS
      if (plus.os.name.toLowerCase() === 'ios') {
        const CBCentralManager = plus.ios.import('CBCentralManager');
        const centralManager = new CBCentralManager();
        const state = centralManager.state();
        plus.ios.deleteObject(centralManager);
        plus.ios.deleteObject(CBCentralManager);
        
        // 检查蓝牙状态：CBManagerStatePoweredOn = 5
        if (state !== 5) {
          uni.showModal({
            title: '提示',
            content: '请先开启手机蓝牙',
            showCancel: false
          });
          return;
        }
      }
      // #endif
      
      uni.showLoading({
        title: '正在开启蓝牙...'
      });
      
      const initialized = await initBluetooth();
      
      uni.hideLoading();
      
      if (initialized) {
        uni.showToast({
          title: '蓝牙已开启',
          icon: 'success'
        });
      }
    } catch (error) {
      uni.hideLoading();
      console.error('开启蓝牙失败:', error);
      uni.showToast({
        title: '开启蓝牙失败: ' + (error.errMsg || '未知错误'),
        icon: 'none'
      });
    }
  }
};

// ArrayBuffer转16进制字符串
const ab2hex = (buffer) => {
  if (!buffer) return '';
  
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    (bit) => ('00' + bit.toString(16)).slice(-2)
  );
  return hexArr.join('');
};

// 生命周期钩子
onMounted(() => {
  // 检查小程序是否配置了蓝牙功能
  // #ifdef MP-WEIXIN
  try {
    const accountInfo = uni.getAccountInfoSync();
    if (accountInfo && accountInfo.miniProgram) {
      console.log('当前小程序版本类型:', accountInfo.miniProgram.envVersion);
      // 在开发版、体验版提示检查蓝牙配置
      if (['develop', 'trial'].includes(accountInfo.miniProgram.envVersion)) {
        setTimeout(() => {
          uni.showModal({
            title: '开发提示',
            content: '请确保已在 manifest.json 中正确配置蓝牙权限，并在小程序管理后台添加"蓝牙"相关功能',
            showCancel: false
          });
        }, 1000);
      }
    }
  } catch (error) {
    console.error('获取小程序账号信息失败:', error);
  }
  // #endif
  
  // 尝试初始化蓝牙
  setTimeout(() => {
    initBluetooth().then(success => {
      if (!success) {
        // 初始化失败，显示额外的提示信息
        setTimeout(() => {
          uni.showModal({
            title: '蓝牙功能异常',
            content: '可能是以下原因：\n1. 设备蓝牙未开启\n2. 没有授予蓝牙权限\n3. 小程序配置问题\n\n您可以尝试开启设备蓝牙后点击"打开蓝牙"按钮重试。',
            confirmText: '我知道了',
            showCancel: false
          });
        }, 1500);
      }
    });
  }, 500);
});

onBeforeUnmount(() => {
  // 组件销毁前关闭蓝牙连接
  if (connectedDevice.value) {
    uni.closeBLEConnection({
      deviceId: connectedDevice.value.deviceId
    });
  }
  
  // 停止扫描
  if (isScanning.value) {
    uni.stopBluetoothDevicesDiscovery();
  }
  
  // 关闭蓝牙适配器
  if (isBluetoothEnabled.value) {
    uni.closeBluetoothAdapter();
  }
  
  // 取消监听
  uni.offBluetoothAdapterStateChange();
  uni.offBluetoothDeviceFound();
  uni.offBLEConnectionStateChange();
  uni.offBLECharacteristicValueChange();
});
</script>

<style lang="scss">
.xl-bluetooth-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 15px;
  box-sizing: border-box;
  
  .bluetooth-status {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    margin-bottom: 15px;
    background-color: #f8f8f8;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    
    .status-indicator {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      background-color: #ff5252;
      margin-right: 10px;
      
      &.active {
        background-color: #4caf50;
      }
    }
    
    .status-text {
      flex: 1;
      font-size: 14px;
      color: #333;
    }
    
    .action-btn {
      padding: 5px 12px;
      border-radius: 4px;
      background-color: #007AFF;
      color: #fff;
      font-size: 12px;
      
      &:active {
        opacity: 0.8;
      }
    }
  }
  
  .device-section {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-bottom: 15px;
    overflow: hidden;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 15px;
      border-bottom: 1px solid #eee;
      
      .section-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
      
      .scan-btn {
        display: flex;
        align-items: center;
        padding: 5px 12px;
        border-radius: 4px;
        background-color: #007AFF;
        color: #fff;
        font-size: 12px;
        
        .loader {
          width: 12px;
          height: 12px;
          border: 2px solid rgba(255, 255, 255, 0.3);
          border-radius: 50%;
          border-top-color: #fff;
          animation: spin 1s linear infinite;
          margin-left: 8px;
        }
        
        &:active {
          opacity: 0.8;
        }
      }
    }
    
    .device-list {
      max-height: 300px;
      
      .empty-list {
        padding: 30px;
        text-align: center;
        color: #999;
        font-size: 14px;
      }
      
      .device-item {
        display: flex;
        align-items: center;
        padding: 12px 15px;
        border-bottom: 1px solid #f0f0f0;
        
        &:active {
          background-color: #f9f9f9;
        }
        
        &.connected {
          background-color: #f0f7ff;
        }
        
        .device-icon {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background-color: #eee;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 12px;
          position: relative;
          overflow: hidden;
          
          &.connected {
            background-color: #e1f5fe;
          }
          
          &:before {
            content: "";
            position: absolute;
            width: 20px;
            height: 20px;
            background-color: #9e9e9e;
            border-radius: 50%;
            z-index: 1;
          }
          
          .signal-strength {
            position: absolute;
            bottom: 0;
            left: 0;
            height: 4px;
            background-color: #4caf50;
            z-index: 2;
          }
        }
        
        .device-info {
          flex: 1;
          overflow: hidden;
          
          .device-name {
            font-size: 15px;
            color: #333;
            margin-bottom: 3px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .device-id {
            font-size: 12px;
            color: #999;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        
        .device-status {
          font-size: 12px;
          color: #007AFF;
          padding-left: 10px;
        }
      }
    }
  }
  
  .connected-device {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 15px;
      border-bottom: 1px solid #eee;
      
      .section-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
      
      .disconnect-btn {
        padding: 5px 12px;
        border-radius: 4px;
        background-color: #ff5252;
        color: #fff;
        font-size: 12px;
        
        &:active {
          opacity: 0.8;
        }
      }
    }
    
    .device-detail {
      padding: 15px;
      border-bottom: 1px solid #eee;
      
      .detail-row {
        display: flex;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .detail-label {
          width: 80px;
          font-size: 14px;
          color: #666;
        }
        
        .detail-value {
          flex: 1;
          font-size: 14px;
          color: #333;
        }
      }
    }
    
    .device-operations {
      display: flex;
      padding: 15px;
      
      .operation-btn {
        flex: 1;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #007AFF;
        color: #fff;
        border-radius: 4px;
        font-size: 14px;
        margin: 0 5px;
        
        &:first-child {
          margin-left: 0;
        }
        
        &:last-child {
          margin-right: 0;
        }
        
        &:active {
          opacity: 0.8;
        }
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 